package com.leetcode.partition11;

import java.io.*;

/**
 * @author `RKC`
 * @date 2022/2/12 17:58
 */
public class LC1020飞地的数量_dfs {

    private static final int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
    private static int[][] graph;
    private static int n = 0, m = 0;

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        String[] ss = reader.readLine().split(" ");
        int n = Integer.parseInt(ss[0]), m = Integer.parseInt(ss[1]);
        int[][] grid = new int[n][m];
        for (int i = 0; i < n; i++) {
            ss = reader.readLine().split(" ");
            for (int j = 0; j < m; j++) grid[i][j] = Integer.parseInt(ss[j]);
        }
        writer.write(numEnclaves(grid) + "\n");
        writer.flush();
    }

    public static int numEnclaves(int[][] grid) {
        n = grid.length;
        m = grid[0].length;
        graph = grid;
        for (int i = 0; i < n; i++) {
            if (grid[i][0] == 1) {
                grid[i][0] = 0;
                dfs(i, 0);
            }
            if (grid[i][m - 1] == 1) {
                grid[i][m - 1] = 0;
                dfs(i, m - 1);
            }
        }
        for (int j = 0; j < m; j++) {
            if (grid[0][j] == 1) {
                grid[0][j] = 0;
                dfs(0, j);
            }
            if (grid[n - 1][j] == 1) {
                grid[n - 1][j] = 0;
                dfs(n - 1, j);
            }
        }
        int ans = 0;
        for (int i = 1; i < n - 1; i++) {
            for (int j = 1; j < m - 1; j++) ans += grid[i][j];
        }
        return ans;
    }

    private static void dfs(int x, int y) {
        for (int[] dir : dirs) {
            int nx = x + dir[0], ny = y + dir[1];
            if (nx < 0 || nx >= n || ny < 0 || ny >= m || check(nx, ny)) continue;
            if (graph[nx][ny] == 0) continue;
            graph[nx][ny] = 0;
            dfs(nx, ny);
        }
    }

    private static boolean check(int x, int y) {
        return x == 0 || x == n - 1 || y == 0 || y == m - 1;
    }
}
